package org.zhss.demo.redis.expire;

import redis.clients.jedis.Jedis;

/** 支持超时自动释放的分布式锁案例 */
public class TimeoutDistributeLockDemo {

  private Jedis jedis = new Jedis("192.168.150.201");

  /**
   * 加锁
   *
   * @param key
   * @param value
   */
  public Boolean lock(String key, String value, int timeout) {
    Long result = jedis.setnx(key, value);
    jedis.expire(key, timeout);
    return result > 0;
  }

  /**
   * 解锁
   *
   * @param key
   */
  public void unlock(String key) {
    jedis.del(key);
  }

  public static void main(String[] args) {
    TimeoutDistributeLockDemo demo = new TimeoutDistributeLockDemo();
    demo.lock("test_key", "test_value", 10);
    Boolean result = demo.lock("test_key", "test_value", 10);
    System.out.println("第二次加锁结果：" + (result ? "成功" : "失败"));
    demo.unlock("test_key");
    //
  }
}
